package com.mypackage.diary.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import com.mypackage.diary.mymodel.User;
import com.mypackage.diary.service.user.UserService;


@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {


	@Autowired
	private UserService userService;
	
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@Override
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		// get username and password from authentication
		String username = authentication.getName();
		String password = authentication.getCredentials().toString();

		// load user from email
		User user = (User) userService.loadUserByUsername(username);

		if (user == null) {
			throw new BadCredentialsException("Username not found.");
		}

		if (!password.equals(user.getPassword())) {
			throw new BadCredentialsException("Wrong password.");
		}
	
		// return new user
		return new UsernamePasswordAuthenticationToken(user, password,
				user.getAuthorities());
	}

	@Override
	public boolean supports(Class<?> authentication) {

		return true;
	}

}
